package com.cheyunkeji.er.activity.fast_evaluate;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.adapter.fastevaluate.EvaluateRecordsAdapter;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.fast_evaluate.FastEvaluateRecord;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.utils.ChannelInfoUtil;
import com.cheyunkeji.er.view.SDialog;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.SwipeLayout;
import com.cheyunkeji.er.view.TopBar;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;

public class EvaluateRecordActivity extends BaseActivity
    implements AdapterView.OnItemClickListener,
        AdapterView.OnItemLongClickListener,
        SDialog.SDialog2Listener,
        OnRefreshListener,
        OnLoadMoreListener {

  private static final String TAG = EvaluateRecordActivity.class.getSimpleName();

  //    每页数据量
  private static final int COUNTS_PER_PAGE = 10;

  //    当前列表状态 STATE_REFRESH : 下拉刷新 ，STATE_LOADMORE : 上拉加载更多
  private static int CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;

  //     当前页数
  private static int CURRENT_LOAD_PAGE = 1;
  //    搜索关键字
  private static String KEY_WORDS = "";
  //    删除成功
  private static final int DELETE_OK = 0x11;

  //    @BindView(R.id.v_topbar)
  //    TopBar vTopbar;
  //    @BindView(R.id.ib_search)
  //    ImageButton ibSearch;
  //    @BindView(R.id.et_search_content_record)
  //    EditText etSearchContentRecord;

  @BindView(R.id.leftBut)
  ImageButton leftBut;

  @BindView(R.id.searchText)
  EditText searchText;

  @BindView(R.id.tv_search_content)
  TextView tvSearchContent;

  @BindView(R.id.ll_empty_content_display)
  LinearLayout llEmptyContentDisplay;

  @BindView(R.id.swipe_target)
  ListView lvRecordList;

  @BindView(R.id.swipe_layout)
  SwipeLayout swipeLayout;

  @BindView(R.id.activity_evaluate_record)
  LinearLayout activityEvaluateRecord;
  //    @BindView(R.id.tv_item_count)
  //    TextView tvItemCount;

  @BindView(R.id.totleText)
  TextView totleText;

  //    当前长按下的item的position
  private int currentItemLongClickedPosition = 0;
  private SDialog dialog;

  private EvaluateRecordsAdapter adapter;

  private ArrayList<FastEvaluateRecord> dataList;

  private Handler uiRefreshHandler =
      new Handler() {

        @Override
        public void handleMessage(Message msg) {
          switch (msg.what) {
            case SwipeLayout.STATE_NORMAL:
              if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
                onRefreshSuccessed((ArrayList<FastEvaluateRecord>) msg.obj);
              } else {
                onLoadMoreSuccessed((ArrayList<FastEvaluateRecord>) msg.obj);
              }
              break;
            case SwipeLayout.STATE_SEARCH_BY_KEYWORD:
              if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
                onRefreshSuccessed((ArrayList<FastEvaluateRecord>) msg.obj);
              } else {
                onLoadMoreSuccessed((ArrayList<FastEvaluateRecord>) msg.obj);
              }
              break;
            case DELETE_OK:
              swipeLayout.setRefreshing(true);
              onRefresh();
              break;
            default:
              break;
          }
        }
      };

  /**
   * 上拉加载成功刷新
   *
   * @param newList
   */
  private void onLoadMoreSuccessed(ArrayList<FastEvaluateRecord> newList) {
    if (newList != null) {
      if (newList.size() != 0) {
        swipeLayout.endLoadMore();
        dataList.addAll(newList);
        adapter.notifyDataSetChanged();
        CURRENT_LOAD_PAGE++;
      } else {
        swipeLayout.endLoadMore();
        swipeLayout.setLoadMoreEnabled(false);
      }
    }
  }

  private void onRefreshSuccessed(ArrayList<FastEvaluateRecord> newList) {
    if (newList != null && newList.size() != 0) {
      hideEmptyView();
      dataList.clear();
      dataList.addAll(newList);
      adapter.notifyDataSetChanged();
      CURRENT_LOAD_PAGE++;
    } else if (newList.size() == 0) {
      showContentEmptyView();
      dataList.clear();
      adapter.notifyDataSetChanged();
    }
    swipeLayout.endRefresh();
  }

  @Override
  protected void init() {
    setContentView(R.layout.er_activity_evaluate_record2);
    ButterKnife.bind(this);
    KEY_WORDS = "";
    dataList = new ArrayList<>();
    adapter = new EvaluateRecordsAdapter(dataList, this);
    lvRecordList.setAdapter(adapter);
    lvRecordList.setOnItemClickListener(this);
    lvRecordList.setOnItemLongClickListener(this);
  }

  @Override
  protected void initView() {
    dialog =
        new SDialog(
            this,
            R.string.t_message_title,
            getResources().getString(R.string.ensure_delete_record),
            this,
            SDialog.TYPE_2_BTN);

    //        ibSearch.setOnClickListener(this);
    swipeLayout.setOnRefreshListener(this);
    swipeLayout.setOnLoadMoreListener(this);

    searchText.setOnEditorActionListener(
        new TextView.OnEditorActionListener() {
          @Override
          public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH
                || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
              // 关闭软键盘
              closeKeyword();
              KEY_WORDS = searchText.getText().toString().trim();
              swipeLayout.setRefreshing(true);
              onRefresh();
              return true;
            } else {
              return false;
            }
          }
        });

    leftBut.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        finish();
      }
    });
  }

  @Override
  protected void initData() {
  }

  @Override
  protected void onResume() {
    super.onResume();
    swipeLayout.setRefreshing(true);
    onRefresh();
  }

  private void hideEmptyView() {
    // swipeLayout.setVisibility(View.VISIBLE);
    llEmptyContentDisplay.setVisibility(View.INVISIBLE);
  }

  private void closeKeyword() {
    View view = getWindow().peekDecorView();
    if (view != null) {
      InputMethodManager inputmanger =
          (InputMethodManager) (this.getSystemService(Context.INPUT_METHOD_SERVICE));
      inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
  }

  private void showContentEmptyView() {
    // swipeLayout.setVisibility(View.INVISIBLE);
    if (!TextUtils.isEmpty(KEY_WORDS)) {
      llEmptyContentDisplay.setVisibility(View.VISIBLE);
      tvSearchContent.setText(KEY_WORDS);
    } else {
      llEmptyContentDisplay.setVisibility(View.INVISIBLE);
    }
  }

  private void loadRecordListData(int page, int rows, final String keyWord) {
    HashMap<String, String> params = new HashMap<>();
    //        params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
    //        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
    params.put("page", String.valueOf(page));
    params.put("rows", String.valueOf(rows));
    if (!TextUtils.isEmpty(keyWord)) {
      params.put("keyword", keyWord);
    }
    ApiClient.postForm(
        HttpConstants.FAST_EVALUATE_RECORD_LIST,
        params,
        new RespCallback<List<FastEvaluateRecord>>() {
          @Override
          protected void onRequestFailed(String msg) {
            SToast.show(msg);
          }

          @Override
          protected void onMsgCount(int rows) {
            super.onMsgCount(rows);
            setItemCount(rows);
          }

          @Override
          protected void onSuccess(List<FastEvaluateRecord> data) {
            Message msg = uiRefreshHandler.obtainMessage();
            msg.what =
                TextUtils.isEmpty(keyWord)
                    ? SwipeLayout.STATE_NORMAL
                    : SwipeLayout.STATE_SEARCH_BY_KEYWORD;
            msg.obj = data;
            uiRefreshHandler.sendMessage(msg);
          }

          @Override
          public void onError(Exception e) {
            super.onError(e);
            if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
              swipeLayout.endRefresh();
            } else if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_LOADMORE) {
              swipeLayout.endLoadMore();
            }
          }
        });
  }

  public void setItemCount(int itemCount) {
    totleText.setText(String.format("共%1$s条数据", String.valueOf(itemCount)));
    showTips();
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
        //            case R.id.ib_search:
        //                KEY_WORDS = etSearchContentRecord.getText().toString().trim();
        //                swipeLayout.setRefreshing(true);
        //                onRefresh();
        //
        //                break;
      default:
        break;
    }
  }

  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    FastEvaluateRecord record = dataList.get(position);
    String h5 = record.getH5();
    String pid = record.getPid();
    String push_type = record.getPush_type();
    String push_archive_type = record.getPush_archive_type();
    String spec_name = record.getSpec_name();
    Log.e(TAG, "onResponse:  HTML5" + h5);
    Log.e(TAG, "onResponse:  pid " + pid);
    Intent intent = new Intent(EvaluateRecordActivity.this, FastEvaluateReportActivity.class);
    intent.putExtra(
        "data", new String[] {h5, pid, push_type, push_archive_type, spec_name, record.getZqb()});
    startActivity(intent);
  }

  @Override
  public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    //       判断是否有删除权限
    if (ChannelInfoUtil.getCurrentChannelInfo().getIsadmin() == 1) {
      dialog.show();
      currentItemLongClickedPosition = position;
    } else if (ChannelInfoUtil.getCurrentChannelInfo().getAuth_list().getRa().size() > 0) {
      for (int i = 0;
          i < ChannelInfoUtil.getCurrentChannelInfo().getAuth_list().getRa().size();
          i++) {
        if (ChannelInfoUtil.getCurrentChannelInfo().getAuth_list().getRa().get(i) == 4) {
          dialog.show();
          currentItemLongClickedPosition = position;
          break;
        }
      }
    }
    return true;
  }

  @Override
  public void onClick(boolean l, View view) {
    if (!l && !TextUtils.isEmpty(dataList.get(currentItemLongClickedPosition).getPid())) {
      HashMap<String, String> params = new HashMap<>();
      //            params.put("authkey",
      // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
      //            params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
      // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
      params.put("pid", dataList.get(currentItemLongClickedPosition).getPid());
      ApiClient.postForm(
          HttpConstants.FAST_EVALUATE_DELETE_RECORD,
          params,
          new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
              // 网络异常
              if (e instanceof UnknownHostException || e instanceof SocketException) {
                SToast.show(R.string.tip_network_error, Gravity.CENTER);
                return;
              }
            }

            @Override
            public void onResponse(String response, int id) {
              try {
                JSONObject obj = new JSONObject(response);
                if (obj.optInt("code", 0) == 1) {
                  SToast.show("删除成功");
                  Message msg = uiRefreshHandler.obtainMessage();
                  msg.what = DELETE_OK;
                  uiRefreshHandler.sendMessage(msg);
                } else {
                  SToast.show(obj.optString("msg"));
                }
              } catch (JSONException e) {
                e.printStackTrace();
              }
            }

            @Override
            public void onBefore(Request request, int id) {
              showDialog();
            }

            @Override
            public void onAfter(int id) {
              dismissDialog();
            }
          });
    }
  }

  @Override
  public void onRefresh() {
    CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;
    CURRENT_LOAD_PAGE = 1;
    loadRecordListData(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE, KEY_WORDS);
    swipeLayout.setLoadMoreEnabled(true);
  }

  @Override
  public void onLoadMore() {
    CURRENT_REFRESH_STATE = SwipeLayout.STATE_LOADMORE;
    loadRecordListData(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE, KEY_WORDS);
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    uiRefreshHandler.removeCallbacksAndMessages(null);
  }

  private void showTips() {
    totleText.setVisibility(View.VISIBLE);
    totleText.clearAnimation();
    AlphaAnimation animation = new AlphaAnimation(1f, 0f);
    animation.setDuration(3000);
    totleText.startAnimation(animation);
    totleText.setVisibility(View.GONE);
  }
}
